package org.springblade.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.app.constant.AppCategoryConstant;
import org.springblade.app.constant.ShySystemConstant;
import org.springblade.app.entity.AppInfoEntity;
import org.springblade.app.entity.AppUserEntity;
import org.springblade.app.feign.IAppClient;
import org.springblade.app.feign.IIotAppClient;
import org.springblade.app.feign.ISubAppClient;
import org.springblade.app.feign.entity.SubAppInfoEntity;
import org.springblade.app.service.IAppInfoService;
import org.springblade.app.service.IAppUserService;
import org.springblade.app.vo.AppInfoVO;
import org.springblade.applicationapi.entity.App;
import org.springblade.applicationapi.props.AppBuiltinProperties;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangyr
 * @version 1.0
 * @date 2022-08-22 18:10
 * @description 应用管理
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/shy/app")
@Api(value = "应用表", tags = "应用表")
@Slf4j
public class ShyAppController {

	private final IAppInfoService app_infoService;
	private final IAppUserService app_userService;
	private final ISubAppClient subAppClient;
	private final IAppClient appClient;
	private final AppBuiltinProperties appBuiltinProperties;
	private final IIotAppClient iotAppClient;

	/**
	 * 所有应用-添加排序-管理权限的应用放在前面
	 */
	@GetMapping("/list/all-sort")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "有应用-添加排序-管理权限的应用放在前面-不含内置", notes = "传入app_info")
	public R<List<AppInfoVO>> listAllSort(@ApiParam(value = "name，应用名称") @RequestParam(required = false) String name,
										  @ApiParam(value = "category，应用类型") @RequestParam(required = false) String category) {
		List<AppInfoVO> allApp = getAllApp(name, category);
		//去除掉其中属于内置应用的应用
		final List<AppInfoVO> collect = allApp.stream().filter(appInfoVO -> !AppCategoryConstant.BUILT_IN_APP.equals(appInfoVO.getCategory())).collect(Collectors.toList());
		return R.data(collect);
	}

	/**
	 * 内置应用集合
	 */
	@GetMapping("/list/all-sort-builtIn")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "自建应用集合", notes = "传入app_info")
	public R<List<AppInfoVO>> listAllSortBuiltIn(@ApiParam(value = "name，应用名称") @RequestParam(required = false) String name,
												 @ApiParam(value = "category，应用类型") @RequestParam(required = false) String category) {
		List<AppInfoVO> allApp = getAllApp(name, category);
		//筛选属于内置应用的应用
		final List<AppInfoVO> collect = allApp.stream().filter(appInfoVO -> AppCategoryConstant.BUILT_IN_APP.equals(appInfoVO.getCategory())).collect(Collectors.toList());
		return R.data(collect);
	}


	/**
	 * 根据用户名或类型查询应用列表
	 * @param name
	 * @param category
	 * @return
	 */
	private List<AppInfoVO> getAllApp(String name, String category){
		// 设置查询条件
		LambdaQueryWrapper<AppInfoEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		if (StringUtil.isNotBlank(name)){
			lambdaQueryWrapper.like(AppInfoEntity::getName, "%" + name + "%");
		}
		if (StringUtil.isNotBlank(category)){
			lambdaQueryWrapper.eq(AppInfoEntity::getCategory, category);
		}
		List<AppInfoEntity> appInfoList = app_infoService.list(lambdaQueryWrapper.orderByAsc(AppInfoEntity::getSort).orderByAsc(AppInfoEntity::getCreateTime));
		List<AppInfoVO> infoVOList = BeanUtil.copy(appInfoList, AppInfoVO.class);
		// 设置所有应用设置权限
		infoVOList.forEach(appInfoVO -> appInfoVO.setIsOperate(1));
		// 超管返回所有应用
		if (AuthUtil.isAdministrator()){
			return infoVOList;
		}
		BladeUser user = AuthUtil.getUser();
		if (user == null){
			return null;
		}
		// 当前用户子应用列表
		List<AppUserEntity> userEntityList = app_userService.list(Wrappers.<AppUserEntity>lambdaQuery().eq(AppUserEntity::getLinkId, user.getUserId()));
		List<String> appIdList = userEntityList.stream().map(AppUserEntity::getAppId).collect(Collectors.toList());
		// 当前用户为普通成员子应用列表
		List<AppUserEntity> normalUserList = userEntityList.stream().filter(userEntity -> userEntity.getType() == 0).collect(Collectors.toList());
		List<String> normalAppIdList = normalUserList.stream().map(AppUserEntity::getAppId).collect(Collectors.toList());
		infoVOList = infoVOList.stream().filter(info -> appIdList.contains(info.getSubAppId())).peek(info -> {
			if (normalAppIdList.contains(info.getSubAppId())){
				info.setIsOperate(0);
			}
		}).collect(Collectors.toList());
		return infoVOList;
	}


	/**
	 * 获取密钥
	 */
	@GetMapping("/getSecret")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "获取密钥", notes = "传入app_info")
	public R getSecret(@ApiParam(value = "应用编号") @RequestParam String subAppId) {
		AppInfoEntity one = app_infoService.getOne(Wrappers.<AppInfoEntity>query().lambda().eq(AppInfoEntity::getSubAppId, subAppId));
		if (one != null) {
			return R.data(one.getSecret());
		}
		return R.fail("未查询到应用！");
	}

	/**
	 * @return 物联网应用信息
	 */
	private App getApp(String category) {
		List<App> appList = appBuiltinProperties.getApp();
		List<App> lowList = appList.stream().filter(app -> category.equals(app.getAlias())).collect(Collectors.toList());
		if (lowList.size() > 0) {
			return lowList.get(0);
		} else {
			log.error("未配置{}应用信息！", category);
			return null;
		}
	}

	/**
	 * 新增应用
	 */
	@PostMapping("/add")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "新增应用", notes = "传入app_info")
	@Transactional
	public R<AppInfoEntity> add(@RequestBody AppInfoEntity appInfoEntity) {

		//默认参数
		appInfoEntity.setStatus(0);
		appInfoEntity.setOwnerId(AuthUtil.getUserId());
		//判断当前应用所属类型
		String category = appInfoEntity.getCategory();
		String subAppId = null;
		switch (category) {
			case AppCategoryConstant.SELF_BUILT_APP:
				App lowApp = getApp("LCDP");
				if (lowApp == null) {
					return R.fail("请配置低代码服务信息！");
				}
				String defaultAppId = lowApp.getAppId();
				String defaultAppSecret = lowApp.getAppSecret();
				Long defaultId = lowApp.getId();
				String defaultMainUrl = lowApp.getMainUrl();
				String defaultCallbackUrl = lowApp.getCallbackUrl();

				//将新增的命令发送到子应用，接收子应用返回的应用id
				SubAppInfoEntity subApp = new SubAppInfoEntity();
				subApp.setCreateUser(appInfoEntity.getOwnerId());
				subApp.setName(appInfoEntity.getName());
				subApp.setDescribe(appInfoEntity.getDescribe());
				subApp.setOwnerId(appInfoEntity.getOwnerId());
				subApp.setLogo(appInfoEntity.getLogo());
				subApp.setAlias(appInfoEntity.getAlias());
				subApp.setCreateTime(new Date());
				subApp.setSort(appInfoEntity.getSort());
				subApp.setIsDeleted(BladeConstant.DB_NOT_DELETED);
				R<SubAppInfoEntity> subAppInfoEntityR = subAppClient.save(subApp);
				if (subAppInfoEntityR.getCode() == 200) {
					SubAppInfoEntity data = subAppInfoEntityR.getData();
					if (data != null) {
						subAppId = data.getAppId();
					}
				}
				if (StringUtil.isBlank(subAppId)) {
					return R.fail("新增失败！请联系管理员");
				}
				//在门户新增应用，初始应用状态为未发布
				appInfoEntity.setSubAppId(subAppId);
				appInfoEntity.setAppId(defaultAppId);
				appInfoEntity.setSecret(defaultAppSecret);
				appInfoEntity.setLinkLogId(defaultId);
				appInfoEntity.setMainUrl(defaultMainUrl);
				appInfoEntity.setCallbackUrl(defaultCallbackUrl);
				app_infoService.save(appInfoEntity);
				//在成员列表中添加拥有者
				AppUserEntity appUser = new AppUserEntity();
				appUser.setType(ShySystemConstant.SHY_APP_OWNER);
				appUser.setAppId(subAppId);
				appUser.setLinkType(1);
				appUser.setLinkId(AuthUtil.getUserId());
				appUser.setCreateTime(new Date());
				app_userService.save(appUser);
				break;
			case AppCategoryConstant.THIRD_PARTY_APP:
				//第三方应用
				//创建单点登录的应用数据，生成appId与appSecret
				String appSecret = null;
				String appId = null;
				Long linkLogId = null;
				App app = new App();
				app.setAppName(appInfoEntity.getName());
				app.setMainUrl(appInfoEntity.getMainUrl());
				app.setCallbackUrl(appInfoEntity.getCallbackUrl());
				R<App> appR = appClient.addApp(app);
				if (appR.getCode() == 200) {
					App data = appR.getData();
					if (data != null) {
						appId = data.getAppId();
						appSecret = data.getAppSecret();
						linkLogId = data.getId();
					}
				}
				if (StringUtil.isBlank(appId) || StringUtil.isBlank(appSecret)) {
					return R.fail("新增失败！请联系管理员");
				}
				//保存当前应用配置
				subAppId = appId;
				appInfoEntity.setAppId(appId);
				appInfoEntity.setSecret(appSecret);
				appInfoEntity.setSubAppId(appId);
				appInfoEntity.setLinkLogId(linkLogId);
				app_infoService.save(appInfoEntity);
				//在成员列表中添加拥有者
				AppUserEntity appUserForThird = new AppUserEntity();
				appUserForThird.setType(ShySystemConstant.SHY_APP_OWNER);
				appUserForThird.setAppId(subAppId);
				appUserForThird.setLinkType(1);
				appUserForThird.setLinkId(AuthUtil.getUserId());
				appUserForThird.setCreateTime(new Date());
				app_userService.save(appUserForThird);
				break;
			case AppCategoryConstant.BUILT_IN_APP:
				//内置应用
				log.info("内置应用新增暂时不考虑");
				return R.fail("暂时不支持内置应用新增！");
			case AppCategoryConstant.IOT_APP:
				//物联网应用
				App iotApp = getApp("IoT");
				if (iotApp == null) {
					return R.fail("请配置物联网服务信息！");
				}
				String defaultIotAppId = iotApp.getAppId();
				String defaultIotAppSecret = iotApp.getAppSecret();
				Long defaultIotId = iotApp.getId();
				String defaultIotMainUrl = iotApp.getMainUrl();
				String defaultIotCallbackUrl = iotApp.getCallbackUrl();

				//将新增的命令发送到子应用，接收子应用返回的应用id
				SubAppInfoEntity subIotApp = new SubAppInfoEntity();
				subIotApp.setCreateUser(appInfoEntity.getOwnerId());
				subIotApp.setName(appInfoEntity.getName());
				subIotApp.setDescribe(appInfoEntity.getDescribe());
				subIotApp.setOwnerId(appInfoEntity.getOwnerId());
				subIotApp.setLogo(appInfoEntity.getLogo());
				subIotApp.setAlias(appInfoEntity.getAlias());
				subIotApp.setCreateTime(new Date());
				subIotApp.setSort(appInfoEntity.getSort());
				subIotApp.setIsDeleted(BladeConstant.DB_NOT_DELETED);
				R<SubAppInfoEntity> iotAppInfoEntityR = iotAppClient.save(subIotApp);
				if (iotAppInfoEntityR.getCode() == 200) {
					SubAppInfoEntity data = iotAppInfoEntityR.getData();
					if (data != null) {
						subAppId = data.getAppId();
					}
				}
				if (StringUtil.isBlank(subAppId)) {
					return R.fail("新增失败！请联系管理员");
				}
				//在门户新增应用，初始应用状态为未发布
				appInfoEntity.setSubAppId(subAppId);
				appInfoEntity.setAppId(defaultIotAppId);
				appInfoEntity.setSecret(defaultIotAppSecret);
				appInfoEntity.setLinkLogId(defaultIotId);
				appInfoEntity.setMainUrl(defaultIotMainUrl);
				appInfoEntity.setCallbackUrl(defaultIotCallbackUrl);
				app_infoService.save(appInfoEntity);
				//在成员列表中添加拥有者
				AppUserEntity appIotUser = new AppUserEntity();
				appIotUser.setType(ShySystemConstant.SHY_APP_OWNER);
				appIotUser.setAppId(subAppId);
				appIotUser.setLinkType(1);
				appIotUser.setLinkId(AuthUtil.getUserId());
				appIotUser.setCreateTime(new Date());
				app_userService.save(appIotUser);
				break;
			case AppCategoryConstant.TWIN_APP:
				App twinApp = getApp("TWIN");
				if (twinApp == null) {
					return R.fail("请配置数字孪生服务信息！");
				}

				// TODO 获取token
				String token = "xxxx";
				// TODO 创建域
				Long domainId = 1224141613300088L;
				// TODO 保存应用信息

				break;
			default:
				log.error("未定义的应用类型");
				return R.fail("未定义的应用类型！");
		}
		return R.success("操作成功！");
	}

	/**
	 * 修改应用
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "修改应用", notes = "传入app_info")
	@Transactional
	public R<AppInfoEntity> update(@RequestBody AppInfoEntity appInfoEntity) {
		//仅能修改名称，别名，log，描述等
		AppInfoEntity appInfo = new AppInfoEntity();
		appInfo.setId(appInfoEntity.getId());
		appInfo.setName(appInfoEntity.getName());
		appInfo.setAlias(appInfoEntity.getAlias());
		appInfo.setDescribe(appInfoEntity.getDescribe());
		appInfo.setLogo(appInfoEntity.getLogo());
		appInfo.setMainUrl(appInfoEntity.getMainUrl());
		appInfo.setCallbackUrl(appInfoEntity.getCallbackUrl());
		app_infoService.updateById(appInfo);
		if (AppCategoryConstant.SELF_BUILT_APP.equals(appInfoEntity.getCategory())) {
			//同步到子应用
			boolean result = false;
			SubAppInfoEntity subApp = new SubAppInfoEntity();
			subApp.setAppId(appInfoEntity.getSubAppId());
			subApp.setName(appInfoEntity.getName());
			subApp.setDescribe(appInfoEntity.getDescribe());
			subApp.setLogo(appInfoEntity.getLogo());
			subApp.setAlias(appInfoEntity.getAlias());
			R r = subAppClient.updateByAppId(subApp);
			if (r.getCode() == 200) {
				result = true;
			}
			//判断子应用是否执行成功，未成功则手动回滚事务
			if (!result) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.fail("同步修改子应用失败！");
			}
		}

		if (AppCategoryConstant.IOT_APP.equals(appInfoEntity.getCategory())) {
			//同步到子应用
			boolean result = false;
			SubAppInfoEntity subApp = new SubAppInfoEntity();
			subApp.setAppId(appInfoEntity.getSubAppId());
			subApp.setName(appInfoEntity.getName());
			subApp.setDescribe(appInfoEntity.getDescribe());
			subApp.setLogo(appInfoEntity.getLogo());
			subApp.setAlias(appInfoEntity.getAlias());
			R r = iotAppClient.updateByAppId(subApp);
			if (r.getCode() == 200) {
				result = true;
			}
			//判断子应用是否执行成功，未成功则手动回滚事务
			if (!result) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.fail("同步修改子应用失败！");
			}
		}
		if (AppCategoryConstant.TWIN_APP.equals(appInfoEntity.getCategory())){
			// TODO 应用修改
		}
		return R.success("操作成功！");
	}

	/**
	 * 删除应用
	 */
	@GetMapping("/delete")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "删除应用-只能删除自建应用", notes = "传入app_info")
	@Transactional
	public R<AppInfoEntity> delete(@ApiParam(value = "subAppIds") @RequestParam String subAppIds) {
		//逻辑删除门户中应用
		List<AppInfoEntity> list = app_infoService.list(Wrappers.<AppInfoEntity>query().lambda().eq(AppInfoEntity::getCategory, AppCategoryConstant.SELF_BUILT_APP).in(AppInfoEntity::getSubAppId, Func.toStrList(subAppIds)).eq(BaseEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED));
		List<Long> ids = list.stream().map(BaseEntity::getId).collect(Collectors.toList());
		app_infoService.removeByIds(ids);
		// TODO 优诺删除
		//同步到子应用中
		List<String> subApps = list.stream().filter(appInfoEntity -> AppCategoryConstant.SELF_BUILT_APP.equals(appInfoEntity.getCategory())).map(AppInfoEntity::getSubAppId).collect(Collectors.toList());
		boolean result = false;
		R r = subAppClient.removeByAppId(Func.join(subApps, ","));
		if (r.getCode() == 200) {
			result = true;
		}
		//判断子应用是否执行成功，未成功则手动回滚事务
		if (!result) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.fail("删除失败");
		}
		return R.success("操作成功！");
	}

	/**
	 * 删除应用
	 */
	@GetMapping("/deleteThird")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "删除应用-只能删除第三方应用", notes = "传入app_info")
	@Transactional
	public R<AppInfoEntity> deleteThird(@ApiParam(value = "subAppIds") @RequestParam String subAppIds) {
		//逻辑删除门户中应用
		List<AppInfoEntity> list = app_infoService.list(Wrappers.<AppInfoEntity>query().lambda().eq(AppInfoEntity::getCategory, AppCategoryConstant.THIRD_PARTY_APP).in(AppInfoEntity::getSubAppId, Func.toStrList(subAppIds)).eq(BaseEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED));
		log.info("list===" + list);
		List<Long> ids = list.stream().map(BaseEntity::getId).collect(Collectors.toList());
		app_infoService.removeByIds(ids);
		//同步删除单点登录管理的应用信息
		List<Long> linkLogIds = list.stream().map(AppInfoEntity::getLinkLogId).collect(Collectors.toList());
		String join = Func.join(linkLogIds, ",");
		log.info("linkLogIds=========", join);
		R r = appClient.deleteApp(join);
		boolean result = false;
		if (r.getCode() == 200) {
			result = true;
		}
		//判断子应用是否执行成功，未成功则手动回滚事务
		if (!result) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.fail("删除失败");
		}
		return R.success("操作成功！");
	}

	/**
	 * 删除应用
	 */
	@GetMapping("/deleteMain")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "删除应用-都能删", notes = "传入app_info")
	@Transactional
	public R<AppInfoEntity> deleteMain(@ApiParam(value = "subAppIds") @RequestParam String subAppIds) {
		List<AppInfoEntity> list = app_infoService.list(Wrappers.<AppInfoEntity>query().lambda().in(AppInfoEntity::getSubAppId, Func.toStrList(subAppIds)).eq(BaseEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED));
		//逻辑删除门户中第三方
		List<AppInfoEntity> thirdList = list.stream().filter(appInfoEntity -> appInfoEntity.getCategory().equals(AppCategoryConstant.THIRD_PARTY_APP)).collect(Collectors.toList());
		if (thirdList.size() > 0) {
			log.info("thirdList===" + thirdList);
			List<Long> ids = thirdList.stream().map(BaseEntity::getId).collect(Collectors.toList());
			app_infoService.removeByIds(ids);
			//同步删除单点登录管理的应用信息
			List<Long> linkLogIds = thirdList.stream().map(AppInfoEntity::getLinkLogId).collect(Collectors.toList());
			String join = Func.join(linkLogIds, ",");
			log.info("linkLogIds=========", join);
			R r = appClient.deleteApp(join);
			boolean result = false;
			if (r.getCode() == 200) {
				result = true;
			}
			//判断子应用是否执行成功，未成功则手动回滚事务
			if (!result) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.fail("删除失败");
			}
		}
		//删除自建应用
		List<AppInfoEntity> selfList = list.stream().filter(appInfoEntity -> appInfoEntity.getCategory().equals(AppCategoryConstant.SELF_BUILT_APP)).collect(Collectors.toList());
		if (selfList.size() > 0) {
			List<Long> ids = selfList.stream().map(BaseEntity::getId).collect(Collectors.toList());
			app_infoService.removeByIds(ids);
			//同步到子应用中
			List<String> subApps = selfList.stream().filter(appInfoEntity -> AppCategoryConstant.SELF_BUILT_APP.equals(appInfoEntity.getCategory())).map(AppInfoEntity::getSubAppId).collect(Collectors.toList());
			boolean result = false;
			R r = subAppClient.removeByAppId(Func.join(subApps, ","));
			if (r.getCode() == 200) {
				result = true;
			}
			//判断子应用是否执行成功，未成功则手动回滚事务
			if (!result) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.fail("删除失败");
			}
		}
		//删除物联网应用
		List<AppInfoEntity> iotList = list.stream().filter(appInfoEntity -> appInfoEntity.getCategory().equals(AppCategoryConstant.IOT_APP)).collect(Collectors.toList());
		if (iotList.size() > 0) {
			List<Long> ids = iotList.stream().map(BaseEntity::getId).collect(Collectors.toList());
			app_infoService.removeByIds(ids);
			//同步到子应用中
			List<String> subApps = iotList.stream().filter(appInfoEntity -> AppCategoryConstant.IOT_APP.equals(appInfoEntity.getCategory())).map(AppInfoEntity::getSubAppId).collect(Collectors.toList());
			boolean result = false;
			R r = iotAppClient.removeByAppId(Func.join(subApps, ","));
			if (r.getCode() == 200) {
				result = true;
			}
			//判断子应用是否执行成功，未成功则手动回滚事务
			if (!result) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.fail("删除失败");
			}
		}
		return R.success("操作成功！");
	}



	/**
	 * 转让应用
	 */
	@GetMapping("/transferApp")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "转让应用", notes = "传入app_info")
	@Transactional
	public R transferApp(@ApiParam(value = "subAppId,应用编号") @RequestParam String subAppId,
						 @ApiParam(value = "用户id") @RequestParam String userId) {

		AppInfoEntity one = app_infoService.getOne(Wrappers.<AppInfoEntity>query().lambda().eq(AppInfoEntity::getSubAppId, subAppId).eq(BaseEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED));
		if (one != null) {
			Long oldOwnerId = one.getOwnerId();
			one.setOwnerId(Long.valueOf(userId));
			app_infoService.updateById(one);
			//将原拥有者改为管理员
			AppUserEntity appUser = app_userService.getOne(Wrappers.<AppUserEntity>query().lambda().eq(AppUserEntity::getAppId, subAppId).eq(AppUserEntity::getLinkType, 1).eq(AppUserEntity::getLinkId, oldOwnerId));
			if (appUser != null) {
				appUser.setType(ShySystemConstant.SHY_APP_MANAGER);
			} else {
				appUser = new AppUserEntity();
				appUser.setType(ShySystemConstant.SHY_APP_MANAGER);
				appUser.setAppId(subAppId);
				appUser.setLinkType(1);
				appUser.setLinkId(oldOwnerId);
				appUser.setCreateTime(new Date());
			}
			app_userService.saveOrUpdate(appUser);
			//将现在用户设置为拥有者
			AppUserEntity appOwner = app_userService.getOne(Wrappers.<AppUserEntity>query().lambda().eq(AppUserEntity::getAppId, subAppId).eq(AppUserEntity::getLinkType, 1).eq(AppUserEntity::getLinkId, Long.valueOf(userId)));
			if (appOwner != null) {
				appOwner.setType(ShySystemConstant.SHY_APP_OWNER);
			} else {
				appOwner = new AppUserEntity();
				appOwner.setType(ShySystemConstant.SHY_APP_OWNER);
				appOwner.setAppId(subAppId);
				appOwner.setLinkType(1);
				appOwner.setLinkId(Long.valueOf(userId));
				appOwner.setCreateTime(new Date());
			}
			app_userService.saveOrUpdate(appOwner);
			//同步到子应用
			if (AppCategoryConstant.SELF_BUILT_APP.equals(one.getCategory())) {
				R r = subAppClient.transferApp(Long.valueOf(userId), subAppId);
				boolean result = false;
				if (r.getCode() == 200) {
					result = true;
				}
				//判断子应用是否执行成功，未成功则手动回滚事务
				if (!result) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.fail("同步子应用失败！");
				}
			}
			//同步到物联网应用
			if (AppCategoryConstant.IOT_APP.equals(one.getCategory())) {
				R r = iotAppClient.transferApp(Long.valueOf(userId), subAppId);
				boolean result = false;
				if (r.getCode() == 200) {
					result = true;
				}
				//判断子应用是否执行成功，未成功则手动回滚事务
				if (!result) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.fail("同步子应用失败！");
				}
			}
		} else {
			return R.fail("未找到应用！");
		}
		return R.status(true);
	}

}
